<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>人员情况</span>
        <el-button  class='goTo' @click="back">返回</el-button>
      </div>
    </template>
    <div style="margin:5px 5px 20px">
      <span>{{ currentDate }} （今日）</span>
      <!-- <span style="font-size:14px;color:rgb(165, 27, 27)">（选中下面的日期将出现那天可接单的人）</span> -->
      <div style="float:right;display:inline-block;border:1px;">
        <span
            :style="{ width: '25px', height: '15px', background: colors.level1, display: 'inline-block', borderRadius: '4px', marginRight: '5px' }"></span><span style="color:rgb(70, 70, 70)">紧急项目</span>
          <span
            :style="{ width: '25px', height: '15px', background: colors.level2, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span style="color:rgb(70, 70, 70)">正常项目</span>
          <span
            :style="{ width: '25px', height: '15px', background: colors.level3, display: 'inline-block', borderRadius: '4px', margin: '0 5px' }"></span><span style="color:rgb(70, 70, 70)">长期项目</span>
        </div>
    </div>
    <!-- <div style="margin:10px 5px">
      今日可接单：{{ availableMembers.join('，') }}
    </div> -->

    <!-- 使用el-table显示人员和日期任务区间 -->
    <el-table :data="personData" height="74vh" style="width: 100%;" :row-key="rowKey" border
      :cell-class-name="handleCellClassName" :header-cell-class-name="handleHeaderCellClassName">

      <!-- 展开按钮，放在姓名前面 -->
      <el-table-column type="expand" width="50" fixed>
        <template #default="props">
          <!-- 展开后显示项目列表，去掉表头，并添加分隔线 -->
          <div style="border-top: 1px solid #ebeef5; background-color: #f2f2f2;"> <!-- 灰色背景 -->
            <el-table :data="props.row.projects" style="width: 100%;" :show-header="false" border
              :row-class-name="tableRowClassName">
              <el-table-column label="序号" prop="index" width="50" align="center">
                <template #default="scope">
                  {{ scope.$index+1 }}
                </template>
              </el-table-column>
              <el-table-column label="项目名称" prop="product_name" width="180">
                <template #default="scope">
                  <el-tooltip class="item" effect="dark" :content="scope.row.remark || '无备注'" placement="top">
                    <span>{{ scope.row.product_name }}</span>
                  </el-tooltip>
                </template>
              </el-table-column>

              <!-- 日期列 -->
              <el-table-column v-for="(date, index) in dateList" :key="index" :label="formatDateWithDay(date)"
                :min-width="65" align="center">
                <template #default="scope">
                  <div style="position: relative; height: 25px; width: 100%;">
                    <!-- 如果不是周末，显示色块 -->
                    <div v-if="!isWeekend(date) && isDateInRange(date, scope.row.work_date, scope.row.deadline_date)"
                      :style="{
                        backgroundColor: getTaskColor(scope.row.level),
                        borderRadius: '4px',
                        width: '100%',
                        height: '20px',
                        position: 'absolute',
                        top: '0',
                        left: '0'
                      }" class="task-block"></div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>

      <!-- 姓名列 -->
      <el-table-column prop="member" label="姓名" width="180" fixed align="center" sortable />

      <!-- 日期列 -->
      <el-table-column v-for="(date, index) in dateList" :key="index" :label="formatDateWithDay(date)" :min-width="65"
        align="center">
        <template #default="scope">
          <div style="position: relative; height: 25px; width: 100%;">
            <div v-for="task in scope.row.projects" :key="task.id">
              <!-- 如果不是周末，显示色块 -->
              <div v-if="!isWeekend(date) && isDateInRange(date, task.work_date, task.deadline_date)" :style="{
                backgroundColor: getTaskColor(task.level),
                borderRadius: '4px',
                width: '100%',
                height: '20px',
                position: 'absolute',
                top: '0',
                left: '0',
                zIndex: task.level ? 4 - task.level : 1
              }" class="task-block">
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import workApi from '../../api/work'
import { useRouter } from 'vue-router'
const router = useRouter()

const currentDate = new Date().toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' })
const selectedDate = ref(new Date())
const personData = ref([])
const dateList = ref([])
const availableMembers = ref([])
const colors = {
  level1: '#d92222',
  level2: 'rgb(243 202 109)',
  level3: '#cbd1d3'
}

// 唯一标识符
const rowKey = (row) => row.member

// 获取今天前10天和后20天的日期
const getDateRange = () => {
  const today = new Date()
  const start = new Date(today)
  start.setDate(today.getDate() - 5)
  const end = new Date(today)
  end.setDate(today.getDate() + 25)

  const dates = []
  let current = new Date(start)

  while (current <= end) {
    dates.push(new Date(current))
    current.setDate(current.getDate() + 1)
  }

  return dates
}

// 日期列表初始化
dateList.value = getDateRange()

// 获取人员列表和任务信息
const getPersonList = async () => {
  try {
    const res = await workApi.getPersonList()
    const originalData = res.data

    let membersData = {}
    let available = []

    // 构建人员与项目的映射关系
    originalData.forEach((item) => {
      const members = item.member.split(',').map((m) => m.trim())
      members.forEach((member) => {
        if (!membersData[member]) {
          membersData[member] = []
        }
        membersData[member].push({
          id: item.id,
          product_name: item.product_name,
          level: item.level,
          work_date: new Date(item.work_date),
          deadline_date: new Date(item.deadline_date),
          remark: item.remark // 添加项目的备注
        })
      })

      // 如果任务在当天，添加到可接单列表
      const today = new Date(currentDate)
      if (item.work_date <= today && item.deadline_date >= today) {
        available.push(...members)
      }
    })

    // 对成员名按拼音首字母进行排序
    personData.value = Object.keys(membersData)
      .sort((a, b) => a.localeCompare(b, 'zh-CN'))  // 按拼音排序
      .map((member) => ({
        member,
        projects: membersData[member]
      }))

    availableMembers.value = Array.from(new Set(available)) // 去重

  } catch (error) {
    console.error('数据加载错误:', error)
    ElMessage.error('数据加载失败，请重试！')
  }
}


onMounted(async () => {
  await getPersonList()
})

// 判断任务是否在日期范围内
const isDateInRange = (date, startDate, endDate) => {
  // 创建新的 endDate 对象并将其增加一天
  const adjustedEndDate = new Date(endDate);
  adjustedEndDate.setDate(adjustedEndDate.getDate() + 1);
  
  return date >= new Date(startDate) && date <= adjustedEndDate;
};

// 获取任务颜色
const getTaskColor = (level) => {
  if (level == "1") {
    return colors.level1
  } else if (level == "2") {
    return colors.level2
  } else if (level == "3") {
    return colors.level3
  } else {
    return colors.level2
  }
}


const tableRowClassName = ({
  row,
  rowIndex,
}) => {
  return 'warning-row'
}

const isToday = (date) => {
  const today = new Date()
  return date.getDate() === today.getDate() && date.getMonth() === today.getMonth() && date.getFullYear() === today.getFullYear()
}

// 格式化日期和周
const formatDateWithDay = (date) => {
  const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const day = dayNames[date.getDay()];
  return `${date.toLocaleDateString('zh-CN', { day: '2-digit' })} ${day}`;
};

// 判断是否为周末
const isWeekend = (date) => {
  if (!date) {
    return false; // 如果 date 为空，直接返回 false
  }

  const day = date.getDay();
  return day === 0 || day === 6; // 周日(0)和周六(6)是周末
};

// 修改 handleCellClassName 函数，给周末列加灰色背景，同时为当前日期列高亮
const handleCellClassName = ({ rowIndex, columnIndex }) => {
  const date = dateList.value[columnIndex - 2]; // 假设日期列从第3列开始

  if (!date) {
    return ''; // 如果 date 为空，不应用任何类名
  }

  // 如果是周末，返回灰色背景
  if (isWeekend(date)) {
    return 'weekend-column';
  }

  // 如果是今天的日期，返回高亮类名
  if (isToday(date)) {
    return 'highlight-today-column';
  }

  return '';
};

// 修改 handleHeaderCellClassName 函数，给表头中的周末列加灰色背景，同时为当前日期表头加高亮
const handleHeaderCellClassName = ({ columnIndex }) => {
  const date = dateList.value[columnIndex - 2]; // 假设日期列从第3列开始

  if (!date) {
    return ''; // 如果 date 为空，不应用任何类名
  }

  // 如果是周末，返回灰色背景
  if (isWeekend(date)) {
    return 'weekend-header';
  }

  // 如果是今天的日期，返回高亮类名
  if (isToday(date)) {
    return 'highlight-today-header';
  }

  return '';
};

const back = async () => {
  router.push({
    path: '/member_report',
  })
}

</script>

<style scoped>
.el-card {
  height: 99%;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-block {
  height: 20px;
  margin: 2px 0;
  border-radius: 11px;
}


</style>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.highlight-today-column {
  border-left: 2px solid green !important;
  border-right: 2px solid green !important;
}

.highlight-today-header {
  border-left: 2px solid green !important;
  border-right: 2px solid green !important;
  border-top: 10px solid green !important;
}

/* 表头周末背景色 */
.weekend-header {
  background-color: #EFEFEF !important;
  color: rgb(173, 173, 173) !important;
}

/* 周末列的灰色背景 */
.weekend-column {
  background-color: #EFEFEF !important;
}

.goTo {
  float: right;
  margin-right: 10px
}

.el-table .cell{
  font-size:15px;
}

</style>
